#include "AReVi/arSystem.h"
using namespace AReVi;


//---------------------------------
// Classe client ... écoute en udp
//---------------------------------

class Client : public ArObject {
public:
	AR_CLASS(Client)
	AR_CONSTRUCTOR(Client)

protected:
	void _onPolling(const Scheduler::PollingEvent & evt);
	int _sock;
};

AR_CLASS_DEF(Client, ArObject)

Client::Client(ArCW & arCW) : ArObject(arCW) {
	// Ouverture de la connexion UDP
	_sock = ArSystem::openUDP(12345);
	if (_sock < 0) {
		cerr << "unable to open udp connexion on port 12345" << endl;
	}
	else {
		ArSystem::setBlockingFD(_sock, false);
		ArSystem::addReadFDPolling(_sock);
		Scheduler::access()->addPollingCB(thisRef(), &Client::_onPolling);
	}
}

Client::~Client() {
	if (_sock >= 0) ArSystem::closeFD(_sock);
}

void Client::_onPolling(const Scheduler::PollingEvent & evt) {
	char data[513];
	for (unsigned int i = 0; i < evt.readingFD.size(); i++) {
		if (ArSystem::hasReadFDPolling(evt.readingFD[i])) {
			int n = ArSystem::partialReadFD(evt.readingFD[i], data, 512);
			data[n] = '\0';
			cout << data;
		}
	}
}



ArRef<Client> client;

ArRef<Scheduler> simulationInit(void) {
	ArRef<Scheduler> sched = RealTimeScheduler::NEW(1e-3);
	client = Client::NEW();
	return(sched);
}

int main(int argc, char ** argv) {
	ArSystem arevi(argc,argv);

	Client::REGISTER_CLASS();

	ArSystem::simulationLoop(&simulationInit);

	return(0);
}

